package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.RecommendUserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserServiceImpl implements RecommendUserService {

    @Autowired
    private MongoTemplate mongoTemplate;
    //根据当前登录用户id 查询推荐用户
    @Override
    public RecommendUser findRecommendUserByUserId(Long loginUserId) {

        Query query = new Query(
                Criteria.where("toUserId").is(loginUserId)
        )
                .with(Sort.by(Sort.Order.desc("score")))//按照缘分值进行排序
                .skip(0).limit(1);//只查询一条数据

        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }

    /**
     * //根据当前登录用户id 查询多个推荐用户
     */
    @Override
    public PageBeanVo findRecommendUser(Integer pageNumber, Integer pageSize, Long loginUserId) {
        int startIndex = (pageNumber - 1) * pageSize +1;//id为1的用户已经被设置为默认推荐用户   so跳过第一个
        Query query = new Query(
                Criteria.where("toUserId").is(loginUserId)
        )
                .with(Sort.by(Sort.Order.desc("score")))//根据缘分值进行排序
                .skip(startIndex).limit(pageSize);

        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        long counts = mongoTemplate.count(query, RecommendUser.class);
        return new PageBeanVo(pageNumber,pageSize,counts,recommendUserList);
    }

    /**
     * 根据当前登录用户id   和推荐用户id 查询推荐的用户信息
     * @param loginUserId
     * @param recommendUserId
     * @return
     */
    @Override
    public RecommendUser findRecommendUser(Long loginUserId, Long recommendUserId) {

        Query query = new Query(
                Criteria.where("userId").is(recommendUserId)
                        .and("toUserId").is(loginUserId)
        );

        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);

        return recommendUser;
    }
}
